<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use think\Db;
use think\Session;
use think\Validate;

class Question extends Common
{
    public function index()
    {
        $questionRes = db('complain t1')
            ->field('t1.*,t2.name, t3.title')
            ->join('user t2', 't2.id = t1.user_id')
            ->join('complain_category t3', 't3.id = t1.cate_id')
            ->order('id desc')
            ->paginate(5);

        $this->assign('questionRes', $questionRes);
        return view();
    }

    public function feedback()
    {
        $state = input('state') ?: 0;

        $data = Db::name('feedback t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.state' => $state])
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        $this->assign('state', $state);

        return view();
    }

    public function feedbackwatch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }

        $id = input('id/d');

        $name = Db::name('feedback t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.id' => $id])
            ->find();

        if ($name && $name['images']) {
            $name['images'] = explode(',', $name['images']);
        }

        $this->assign('name', $name);
        return $this->fetch();
    }

    public function feedbackadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {
                $feedback = Db::name('feedback')->find($id);

                $db = Db::name('feedback')->where('id', $id)->update(['state' => 1, 'reply' => $post['reply']]);

                if ($post['reply']) {
                    $notice = '关于您的反馈 [' . strip_tags($feedback['content']) . ']。' . $post['reply'];

                    Privatechat::notice($feedback['user_id'], $notice);
                }

                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function feedbackDel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $res = Db::name('feedback')->where(['id'=>$id])->find();
                $db = Db::name('feedback')->where(['id'=>$id])->delete();
                if ($db) {
                    if($res['images']){
                        $images = explode(',', $res['images']);
                        foreach ($images as $key => $value) {
                            \app\service\AliOss::delete($value);
                        }
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    // 批量设置hide
    public function feedbackAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('feedback')->where(['id' => ['in', $post]])->update(['state' => 1, 'reply' => '批量设置已处理']);
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    // 添加问题
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            // var_dump($data);die;
            //验证
            // $validate = validate('article');
            // if (!$validate->check($data)) {
            //     $this->error($validate->getError());
            // }
            $add = db('feedback')->insert($data);
            if ($add) {
                $this->success('添加问题成功！', 'index');
            } else {
                $this->error('添加问题失败！');
            }
            // return;
        }
        return view();
    }

    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            //验证
            // $validate=validate('question');
            // if(!$validate->scene('edit')->check($data)){
            //     $this->error($validate->getError());
            // }

            $save = db('feedback')->update($data);
            if ($save !== false) {
                $this->success('修改问题成功！', 'lst');
            } else {
                $this->error('修改问题失败！');
            }
            return;
        }
        $questions = db('feedback')->field('id,title,content')->find(input('id'));
        $this->assign([
            'questions' => $questions,
        ]);
        return view();
    }

    public function del($id)
    {
        $del = db('complain')->delete($id);
        if ($del) {
            $this->success('删除成功！', 'index');
        } else {
            $this->error('删除失败！');
        }
    }


    // 批量更新排序
    public function desAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            foreach ($_POST['des'] as $k => $v) {
                $id = intval($k);
                $name = intval($v);
                Db::name('article')->where('id', $id)->setField('des', $name);
            }
            $data = ['ret' => '更新排序成功'];
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    // 批量删除
    public function delAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('article')->delete($post);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    // 批量设置hide
    public function all()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('article');
                foreach ($post as $k => $v) {
                    if ($type == 'del') {
                        //   echo "删除成功";
                        $db->delete($v);
                    } else {
                        $db->where('id', $v)->setField('hide', $type);
                    }
                }
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    // 发送消息
    public function mess()
    {
        $id = input('id');
        $this->assign('id', $id);

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$post['content']) {
                return ['err' => '内容不能为空'];
            }

            $content = preg_replace("/<(\/?p.*?)>/si", "", $post['content']);

            $res = Db::name('complain')->where(['id' => $id])->find();
            if (!$res) return ['err' => '发送失败，投诉不存在'];

            Db::name('complain')->where(['id' => $id])->update(['reply' => $content, 'reply_time' => time()]);

            Db::name('sys_message')->insert(['to_user' => $res['user_id'], 'type' => -1, 'context' => json_encode(['id' => $id, 'desc' => '关于您的投诉,' . $content], JSON_UNESCAPED_UNICODE)]);

            if ($res !== false) {
                $data = ['ret' => '发送成功'];

                //action('api/Privatechat/getreadcount', ['user_id' => $res['user_id']]);

                $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . str_replace($_SERVER['PATH_INFO'], '', $_SERVER['REQUEST_URI']) . '/apis/index.php/home/privatechat/';

                curl(str_replace('/index.php/apis', '/apis', $url) . 'getreadcount', json_encode(['user_id' => $res['user_id']]), 0);

            } else {
                $data = ['err' => '发送失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }


    // 消息列表
    public function messlist()
    {
        $id = input('id');

        if ($id) {
            $list = db('complain')
                ->alias('t1')
                ->field('t1.*,t2.name')
                ->join('user t2', 't2.id = t1.user_id')
                ->where(['t1.id' => $id])
                ->order('t1.id desc')
                ->paginate(5);

            if ($list) {
                $this->assign('list', $list);
            } else {
                $data = ['err' => 'id参数错误'];
            }
        }
        $data = $this->fetch();

        return $data;
    }


    public function delmess($id)
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $res = db('feedback')->delete($id);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    //预览
    public function watch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }

        $id = input('id/d');

        $name = db('complain t1')
            ->field('t1.*,t2.name')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.id' => $id])
            ->find();

        if ($name && $name['images']) {
            $name['images'] = explode(',', $name['images']);
        }

        $this->assign('name', $name);
        return $this->fetch();
    }


    //新闻消息
    public function news()
    {
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }

        $data = db('news')->order('des ' . $order . ',id ' . $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加新闻消息
    public function newsadd()
    {
        $id = input("id");

        if (request()->isAjax()) {

            $post = input('post.');

            //开始验证
            $validate = new Validate([
                ['title', 'require|max:100', '标题不能为空|标题长度不能超过100个字符'],
                ['desc', 'require|max:255', '简介不能为空|简介长度不能超过255个字符'],
                ['content', 'require', '内容不能为空'],
            ]);

            if (!$validate->check($post)) {
                return ['err' => $validate->getError()];
            }

            $post['time'] = time();
            $post['content'] = in_content($post['content']);

            if ($post['img']) {
                $image = \think\Image::open(ROOT_PATH . $post['img']);

                $weizhi = strripos($post['img'], '/');
                $riqi = substr($post['img'], $weizhi - 8, 8);
                $img = substr($post['img'], $weizhi + 1);
                $imgthumb = '/public/uploads/' . $riqi . '/thumb300_' . $img;

                $image->thumb(300, 300)->save(ROOT_PATH . $imgthumb);
                $post['imgthumb'] = $imgthumb;
            }

            if (!$id) { //添加数据

                $res = db('news')->insert($post);

                $temp = '添加';

            } else { //修改数据

                $res = db('news')->where('id', $id)->update($post);

                $temp = '修改';

            }

            if ($res) {
                $data = ['ret' => $temp . '成功'];
            } else {
                $data = ['err' => $temp . '失败'];
            }
        } else {
            if ($id) {
                $name = db('news')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //预览
    public function newswatch()
    {
        if (!input('?id')) {
            $this->error("参数错误");
        }

        $id = input('id/d');

        $name = db('news')->where(['id' => $id])->find();

        $this->assign('name', $name);
        return $this->fetch();
    }


    //删除新闻消息
    public function newsdel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('news')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

}